package com.ruoyi.web.controller.cpsp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.cpsp.domain.*;
import com.ruoyi.cpsp.dto.ApprovalRecordModifyDto;
import com.ruoyi.cpsp.mapper.*;
import com.ruoyi.cpsp.service.*;
import com.ruoyi.system.service.ISysDeptService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/cpsp/approvalRecord")
public class ApprovalRecordController {

    @Autowired
    ApprovalRecordService approvalRecordService;

    @Autowired
    ApprovalRecordMapper approvalRecordMapper;

    @Autowired
    private EvaluateRecordMapper evaluateRecordMapper;

    @Autowired
    private RegulationTimesMapper regulationTimesMapper;

    @Autowired
    private EvaluateRecordToEmployeeMapper toEmployeeMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private TeamGroupMapper teamGroupMapper;

    @Autowired
    private EvaluateRecordDetailService detailService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private EvaluateRecordService evaluateRecordService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private EvaluateRecordToEmployeeService toEmployeeService;

    @Autowired
    private RegulationDetailAndTimesService timesService;

    private EmployeeController employeeController = new EmployeeController();


    @ApiOperation("添加违章修改申请记录")
    @PostMapping(value = "add")
    public AjaxResult add(ApprovalRecordModifyDto approvalRecordModifyDto){
        return AjaxResult.success(approvalRecordService.insert(approvalRecordModifyDto));
    }


    @ApiOperation("同意违章修改申请")
    @RequestMapping(value = "agree",method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult agree(@ApiParam(name="id",value="ID",required=true) @RequestParam Integer id) {

        ApprovalRecord record = approvalRecordMapper.selectByPrimaryKey(id);
        int operateType = record.getOperateType();
        int tag = approvalRecordService.agree(id);
        if (tag == 0) {
            return AjaxResult.error("同意申请操作失败！");
        }
        //删除
        if(operateType == 0){
            // 先调用agree函数，再进行删除操作
            int detailId = record.getDetailId();
            AjaxResult ajaxResult1 = deleteDetailUtil(detailId);
            if(!ajaxResult1.containsValue(200)){
                return ajaxResult1;
//              return AjaxResult.error("删除记录失败");
            }
            return AjaxResult.success("通过删除申请并更新数据成功！");
        }
        //修改
        else if(operateType == 1){
            int detailId = record.getDetailId();
            String employeeIdCard = record.getEmployeeIdCard();
            int regulationTypeId = record.getRegulationTypeId();
            int regulationDetailId = record.getRegulationDetailId();
            AjaxResult ajaxResult2 = updateDetailUtil(detailId, employeeIdCard, regulationTypeId,regulationDetailId);
            if(!ajaxResult2.containsValue(200)){
                return ajaxResult2;
//              return AjaxResult.error("修改记录失败");
            }
            return AjaxResult.success("通过修改申请并更新数据成功！");
        }
        else {
            return AjaxResult.error("编辑类型错误");
        }
    }

    @ApiOperation("拒绝违章修改申请")
    @RequestMapping(value = "reject",method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult reject(@ApiParam(name="id",value="ID",required=true) @RequestParam Integer id) {
        return AjaxResult.success(approvalRecordService.reject(id));
    }


    @ApiOperation("查找违章修改申请")
    @RequestMapping(value = "select", method = RequestMethod.GET)
    @ResponseBody
    private AjaxResult select(@RequestParam(defaultValue = "1") Integer pageNum,
                                         @RequestParam(defaultValue = "10") Integer pageSize) {
        List<ApprovalRecord> list = new ArrayList<>();
        PageHelper.startPage(pageNum,pageSize);
        list = approvalRecordService.select();
        PageInfo pageInfo = PageInfo.of(list);
        return AjaxResult.success(pageInfo);
    }

    @ApiOperation("查看违章修改申请前后对比详情")
    @RequestMapping(value = "detail",method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult detail(@ApiParam(name="id",value="ID",required=true) @RequestParam Integer id) {
        return AjaxResult.success(approvalRecordService.detail(id));
    }


    public AjaxResult updateDetailUtil(Integer detailId,
                                       String employeeIdCard,
                                       Integer regulationTypeId,
                                       Integer regulationDetailId) {
        if (detailService.selectDetailById(detailId) != null && employeeIdCard != null && regulationTypeId != null && regulationDetailId != null) {
            EvaluateRecordDetail detail = detailService.selectByPrimaryKey(detailId);
            // 先根据违章id删除该违章记录。
            AjaxResult ajaxResult = deleteDetailUtil(detailId);
            if (!ajaxResult.containsValue(200)) {
                return AjaxResult.error("删除记录失败！");
            }
            // 再根据身份证号，违章类型id，违章细节id重新添加。
            AjaxResult AjaxResult1 = insertDetail(employeeIdCard,regulationTypeId,regulationDetailId, detail.getYear(), detail.getQuarter(), detail.getDateTime());
            if (!AjaxResult1.containsValue(200)) {
                return AjaxResult.error("添加更新后记录失败！");
            }
            return AjaxResult.success("更新违章记录成功！");
        }else {
            return AjaxResult.error("参数不符合要求！");
        }

    }

    private AjaxResult deleteDetailUtil(Integer detailId) {
        EvaluateRecordDetail detail = detailService.selectByPrimaryKey(detailId);
        Integer teamGroupId = detail.getEmployeeGroup();
        TeamGroup teamGroup = teamGroupMapper.selectById(teamGroupId);
        boolean isManageTag = teamGroup != null && teamGroup.getTeamGroupName().contains("管理");
        int year = detail.getYear();
        int session = detail.getQuarter();
        System.out.println(session);
        // 查找evaluate_record表里面的次数。
        EvaluateRecordEntity entity = evaluateRecordService.checkTimes(year, session, detail.getEmployeeIdCard(), detail.getEmployeeDepart(),
                detail.getRegulationTypeId(), detail.getRegulationDetailId());
        // 如果evaluate_record的次数为1，直接删去了，
        if (entity.getTimes() == 1) {
            // 直接删除全部记录。
            List<String> employeeIdCards = toEmployeeService.selectIdCardsByRecordId(entity.getId());
            evaluateRecordService.deleteInfoById(entity.getId());
            toEmployeeService.deleteInfoByRecordId(entity.getId());
            detailService.deleteRecordDetail(detail.getId());
            detailService.updateCurrentPerformanceData(employeeIdCards, null);
            return AjaxResult.success("删除数据成功！");
        }
        // 如果要删除的这条记录，肇事者犯过多次，大于最大次数，减去一次对关联人员扣减比例无影响。
        int maxTimes = timesService.maxTimesByDetailId(detail.getRegulationDetailId());
        entity.setTimes(entity.getTimes() - 1);
        if (entity.getTimes() >= maxTimes) {
            // 更新汇总表的次数.
            evaluateRecordService.updateByIdSelective(entity);
            detailService.deleteRecordDetail(detail.getId());
            return AjaxResult.success("删除数据成功！");
        }

        List<String> employeeIdCards = toEmployeeService.selectIdCardsByRecordId(entity.getId());
        // 如果肇事者违章次数小于最大次数且大于1，还需要更新关联人员的信息。
        toEmployeeService.deleteInfoByRecordId(entity.getId());
        evaluateRecordService.deleteInfoById(entity.getId());
        detailService.deleteRecordDetail(detail.getId());
        detailService.updateCurrentPerformanceData(employeeIdCards, null);
        // 还需要更新evaluate_record表和to_employee表里面的内容。
        entity.setId(null);
        boolean tag = insertToTable(entity, isManageTag);
        return AjaxResult.success("删除数据成功！");
    }

    private boolean insertToTable(EvaluateRecordEntity record, boolean isManageTag) {
        boolean flag = true;
        System.out.println(record.getId());
        // 插入到evaluate_record表。
        int tag = evaluateRecordMapper.insertEvaluateRecord(record);
        System.out.println("tag："+tag);
        if (tag < 1) flag = false;
        // 将关联人员插入到evaluate_record_to_employee表中。
        int recordId = evaluateRecordMapper.selectCurrMaxEvaluateRecordKey();
        // 根据regulationDetailId和times找到每部分的扣减比例。
        RegulationTimes regulationTimes = regulationTimesMapper.selectByDetailIdAndTimes(record.getRegulationDetailId(), record.getTimes());
        EvaluateRecordToEmployee toEmployee = new EvaluateRecordToEmployee();
        EmployeeEntity employee = employeeMapper.selectByCard(record.getEmployeeIdCard());
        // 创建一个list来存储关联人员的
        List<String> employeeIdCards = new ArrayList<>();
        // 肇事者employee.
        if (regulationTimes.getPersonalProportion() > 0) {
            toEmployee.setEvaluateRecordId(recordId);
            toEmployee.setEmployeeIdCard(record.getEmployeeIdCard());
            toEmployee.setProportionOfPunishment(regulationTimes.getPersonalProportion());
            employeeIdCards.add(record.getEmployeeIdCard());
            tag = toEmployeeMapper.insertEvaluateRecordToEmployee(toEmployee);
            if (tag < 1) flag = false;
            System.out.println("肇事者："+toEmployee.getEmployeeIdCard());
        }
        if (isManageTag) {
            detailService.updateCurrentPerformanceData(employeeIdCards, record);
            return flag;
        }
        if (employee.getTeamGroup() != null) {
            // 与肇事者同部门同班组
            if (regulationTimes.getTeamGroupProportion() > 0) {
                List<EmployeeEntity> related = employeeService.selectEmployeesByTeamGroup(employee.getTeamGroup().getId()+"", employee.getDepartment().getDepartmentId());
                if (related.size() > 0) {
                    for (EmployeeEntity rel:related) {
                        TeamGroup teamGroup = employeeService.selectById(employee.getTeamGroup().getId());
                        if (!rel.getIdCard().equals(employee.getIdCard()) && (teamGroup.getBranchManagerId() == null || !teamGroup.getBranchManagerId().equals(rel.getIdCard())) && (teamGroup.getMainManagerId() == null || !teamGroup.getMainManagerId().equals(rel.getIdCard())) ) {// 筛选同一个班组
                            // 如果分管或者主管与肇事者在一个班组，则不加。
                            toEmployee.setEvaluateRecordId(recordId);
                            toEmployee.setEmployeeIdCard(rel.getIdCard());
                            toEmployee.setProportionOfPunishment(regulationTimes.getTeamGroupProportion());
                            tag = toEmployeeMapper.insertEvaluateRecordToEmployee(toEmployee);
                            employeeIdCards.add(rel.getIdCard());
                            if (tag < 1) flag = false;
                            System.out.println("同部门同班组："+toEmployee.getEmployeeIdCard());
                        }
                    }
                }
            }
            // 与肇事者同部门不同班组。
            if (regulationTimes.getDepartmentProportion() > 0) {
                List<EmployeeEntity> related = employeeService.selectEmployeesByDepartment(employee.getDepartment().getDepartmentId());
                if (related.size() > 0) {
                    for (EmployeeEntity rel:related) {
                        TeamGroup teamGroup = employeeService.selectById(employee.getTeamGroup().getId());
                        if (rel.getTeamGroup()== null || !rel.getTeamGroup().equals(employee.getTeamGroup())) {
                            if((teamGroup.getBranchManagerId() == null || !teamGroup.getBranchManagerId().equals(rel.getIdCard())) && (teamGroup.getMainManagerId() == null || !teamGroup.getMainManagerId().equals(rel.getIdCard()))) {
                                toEmployee.setEvaluateRecordId(recordId);
                                toEmployee.setEmployeeIdCard(rel.getIdCard());
                                toEmployee.setProportionOfPunishment(regulationTimes.getDepartmentProportion());
                                tag = toEmployeeMapper.insertEvaluateRecordToEmployee(toEmployee);
                                employeeIdCards.add(rel.getIdCard());
                                if (tag < 1) flag = false;
                                System.out.println("同部门不同班组："+toEmployee.getEmployeeIdCard());
                            }
                        }
                    }
                }
            }
            // 肇事者的分管
            if (regulationTimes.getBranchManagerProportion() > 0) {
                TeamGroup teamGroup = employeeService.selectById(employee.getTeamGroup().getId());
                if (teamGroup.getBranchManagerId() != null) {
                    toEmployee.setEvaluateRecordId(recordId);
                    toEmployee.setEmployeeIdCard(teamGroup.getBranchManagerId());// 得到的是idCard。
                    toEmployee.setProportionOfPunishment(regulationTimes.getBranchManagerProportion());
                    tag = toEmployeeMapper.insertEvaluateRecordToEmployee(toEmployee);
                    employeeIdCards.add(teamGroup.getBranchManagerId());
                    if (tag < 1) flag = false;
                    System.out.println("分管："+toEmployee.getEmployeeIdCard());
                }

            }
            // 肇事者的主管
            if (regulationTimes.getMainManagerProportion() > 0) {
                TeamGroup teamGroup = employeeService.selectById(employee.getTeamGroup().getId());
                if (teamGroup.getMainManagerId() != null) {
                    toEmployee.setEvaluateRecordId(recordId);
                    toEmployee.setEmployeeIdCard(teamGroup.getMainManagerId());
                    toEmployee.setProportionOfPunishment(regulationTimes.getMainManagerProportion());
                    tag = toEmployeeMapper.insertEvaluateRecordToEmployee(toEmployee);
                    employeeIdCards.add(teamGroup.getMainManagerId());
                    if (tag < 1) flag = false;
                    System.out.println("主管："+toEmployee.getEmployeeIdCard());
                }

            }
            detailService.updateCurrentPerformanceData(employeeIdCards, record);
            // 根据employeeIdCard找到关联人员。
            return flag;
        }else {
            //当员工没有班组时，设置部门扣减比例
            if (regulationTimes.getDepartmentProportion() > 0) {
                List<EmployeeEntity> related = employeeService.selectEmployeesByDepartment(employee.getDepartment().getDepartmentId());
                if (related.size() > 0) {
                    for (EmployeeEntity rel:related) {
                        if(!rel.getIdCard().equals(employee.getIdCard())){
                            toEmployee.setEvaluateRecordId(recordId);
                            toEmployee.setEmployeeIdCard(rel.getIdCard());
                            toEmployee.setProportionOfPunishment(regulationTimes.getDepartmentProportion());
                            tag = toEmployeeMapper.insertEvaluateRecordToEmployee(toEmployee);
                            employeeIdCards.add(rel.getIdCard());
                            if (tag < 1) flag = false;
                            //System.out.println("没班组的员工的部门员工id:："+toEmployee.getEmployeeIdCard());
                        }
                    }
                }
            }
            detailService.updateCurrentPerformanceData(employeeIdCards, record);
            return flag;
        }
    }

    private AjaxResult insertDetail(String employeeIdCard, Integer regulationTypeId, Integer regulationDetailId, Integer year, Integer session, String datetime) {
        EvaluateRecordDetail evaluateRecordDetail = new EvaluateRecordDetail();
        EmployeeEntity employee = employeeService.selectByCard(employeeIdCard);
        evaluateRecordDetail.setYear(year);
        evaluateRecordDetail.setQuarter(session);
        evaluateRecordDetail.setEmployeeIdCard(employeeIdCard);
        evaluateRecordDetail.setEmployeeDepart(employee.getDepartment().getDepartmentId());

        evaluateRecordDetail.setRegulationTypeId(regulationTypeId);
        evaluateRecordDetail.setRegulationDetailId(regulationDetailId);
        evaluateRecordDetail.setDateTime(datetime);
        evaluateRecordDetail.setState(1);
        if (employee.getTeamGroup() == null) {
            evaluateRecordDetail.setEmployeeGroup(0);
        }else {
            evaluateRecordDetail.setEmployeeGroup(employee.getTeamGroup().getId());
        }
        int tag = detailService.insertDetail(evaluateRecordDetail);
        if (tag < 1) {
            return AjaxResult.error("插入数据失败！");
        }
        // 插入到detail表之后，需要将相应的信息添加到evaluate_record表中，保存统计出来的信息，并根据违章次数来添加关联人员。
        // 调用evaluate_record表中的插入语句。
        evaluateRecordService.insertEvaluateRecord(evaluateRecordDetail);
        return AjaxResult.success("插入数据成功！");
    }
}
